<template>
  <div class="content">
    <el-button @click="openFormDialog(form,'add')">新增账户</el-button>

    <div style="display: flex;flex-direction: column;align-items: flex-end;">

      <el-table
          :data="userList"
          row-key="id"
          stripe
          :row-style="{height:'40px'}"
          :cell-style="{padding:'0px'}">
        <el-table-column
            prop="username"
            label="用户名">
        </el-table-column>
        <el-table-column
            label="角色">
          <template slot-scope="scope">
            <el-tag
                v-for="role in scope.row.roles"
                :key="role.id">
              {{role.name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="200">
          <template slot-scope="scope">
            <el-button @click="openFormDialog(scope.row,'edit')" type="text" size="small">编辑</el-button>
            <el-button @click="deleteById(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination style="margin-top: 5px"
                     @size-change="currentSizeChange"
                     @current-change="currentChange"
                     :current-page="currentPage"
                     :page-sizes="[10, 20, 30, 40]"
                     :page-size="limit"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <el-dialog title="修改账户信息" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="form" ref="form">
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth"
                        :rules="[
                                      { required: true, message: '请填写完整'}
                                    ]">
            <el-input v-model="form.username" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="密码" prop="password" :label-width="formLabelWidth" v-if="type === 'add'"
                        :rules="[
                                      { required: true, message: '请填写完整'}
                                    ]">
            <el-input v-model="form.password" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model="defaultRoleList" multiple placeholder="请选择角色类型">
              <el-option v-for="role in roles" :value="role.id" :label="role.name" :key="role.id"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>

    </div>

  </div>
</template>

<script>
export default {
  name: "UserList",
  components: {

  },
  data(){
    return{
      page:1,
      limit:10,
      total:0,
      currentPage:1,
      userList: [],
      //所有
      roles:[],
      type:'',
      form:{
        id:'',
        username:'',
        password:'',
        roles:''
      },
      //已经有
      defaultRoleList:[],
      dialogFormVisible:false,
      formLabelWidth:'120px'
    }
  },
  created(){
    this.getDatas()
    this.getRoles()
  },
  methods:{
    getDatas(){
      let url = "user/"+this.page+"/"+this.limit;
      this.$http.get(url).then(res=>{
        if(res.data.code===0){
          this.total = res.data.data.data.total
          this.userList = res.data.data.data.records
        }
      })
    },
    //页面发生改变
    currentChange(value){
      this.page = value
      this.getDatas()
    },
    currentSizeChange(value){
      this.limit = value
      this.getDatas()
    },
    //获取角色列表
    getRoles(){
      let url = "role"
      this.$http.get(url).then(res=>{
        if(res.data.code===0){
          this.roles = res.data.data.data
        }
      })
    },
    //提交表单
    submitForm(formName){
      if(this.form.id){
        let roles = []
        if(this.defaultRoleList){
          for(let item of this.defaultRoleList){
            let obj = {}
            obj.id = item
            roles.push(obj)
          }
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url = "user"
            this.$http.put(url,this.form).then(res=>{
              if(res.data.code===0){
                this.getDatas()
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
              }else{
                this.$message({
                  type:'error',
                  message:res.data.message
                });
              }
            })
          } else {
            return false;
          }
        });
      }else{
        let roles = []
        if(this.defaultRoleList){
          for(let item of this.defaultRoleList){
            let obj = {}
            obj.id = item
            roles.push(obj)
          }
        }
        this.form.roles = roles
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url = "user"
            this.$http.post(url,this.form).then(res=>{
              if(res.data.code===0){
                this.getDatas()
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
              }else{
                this.$message({
                  type:'error',
                  message:res.data.message
                });
              }
            })
          } else {
            return false;
          }
        });
      }
    },
    //打开表单
    openFormDialog(row,type){
      this.dialogFormVisible = true
      this.type = type
      if(type==='add'){
        this.form = {}
        this.defaultRoleList = []
      }
      if(type==='edit'){
        this.form = {...row}
        //角色
        let byUserIdRoleUrl = 'user/role/'+this.form.id
        this.$http.get(byUserIdRoleUrl).then(res=>{
          if(res.data.code===0){
            this.defaultRoleList = res.data.data.data
          }
        })
      }
    },
    //根据ID删除
    deleteById(row) {
      this.$confirm('确定要删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'user/'+row.id
        this.$http.delete(url).then(res=>{
          if(res.data.code===0){
            this.getDatas()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>

</style>
